package com.zm.demo.controller;

import com.zm.demo.service.DemoService;
import com.zm.demo.dto.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
public class Demo1Controller implements DemoService {
    @Autowired
    DiscoveryClient discoveryClient;

    @Override
    public String test1() {
        return "producer service test1";
    }

    @Override
    public int add(int a, int b) {
        int result = a + b;
        List<ServiceInstance> instances = discoveryClient.getInstances("SERVICE-PRODUCER");
        for (ServiceInstance instance : instances) {
            log.info("uri={}，serviceId={}，result={}", instance.getUri(), instance.getServiceId(), result);
        }
        return result;
    }

    @Override
    public User user() {
        User user = new User("张三", 33);
        return user;
    }

    @Override
    public String post() {
        return "post demo";
    }

    /**
     * post对象传参，在实现服务里的参数也必须加上 @RequestBody ，不然获取的对象仍然没有值
     *
     * @param user
     * @return
     */
    @Override
    public String postAndParam(@RequestBody User user) {
        log.info("post name:{}", user.getName());
        return user.toString();
    }

    /**
     * get对象传参，在实现服务里的参数也必须加上 @RequestBody ，不然获取的对象仍然没有值
     *
     * @param user
     * @return
     */
    @Override
    public String getAndParam(@RequestBody User user) {
        log.info("get name:{}", user.getName());
        return user.toString();
    }
}
